package com.dailyblue.javaee.controller;

import com.dailyblue.javaee.bean.User;
import com.dailyblue.javaee.service.UserService;
import com.dailyblue.javaee.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/user_login")
public class UserLoginController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        HttpSession session = request.getSession();
        request.setCharacterEncoding("utf-8");
        String name =request.getParameter("name");
        String password =request.getParameter("password");
        String code = request.getParameter("code");
       // 验证验证码是否正确
        Object sessionCode = session.getAttribute("CODE");
        if (!code.equalsIgnoreCase(sessionCode.toString())) {
            session.setAttribute("ERROR", "验证码错误！");
            response.sendRedirect("session/login.jsp");
            return;
        }
        UserService service = new UserServiceImpl();
        User user = service.login(name, password);
        if (user == null) {
            session.setAttribute("ERROR","账号或者密码错误");
            response.sendRedirect("session/login.jsp");
            return;
        }
        session.setAttribute("USER", user);
        response.sendRedirect("session/index.jsp");
    }
}